﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;

namespace Manager.Tools
{
    public class FileUpload
    {
        private string uploadUrl = ConfigHelper.GetConfigString("ImageUrl");
        public int fileSize = 1024*5;
        private string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };

        public bool DeleteExistFile(string path)
        {
            bool res = true;
            if (System.IO.File.Exists(path))
            {
                try
                {
                    System.IO.File.Delete(path);
                }
                catch
                {
                    res = false;
                }
            }
            return res;
        }

        public string SaveFile(HttpPostedFileBase file,string floder)
        {
            string result = Path.GetFileName(file.FileName);
            string url = "";

            uploadUrl = uploadUrl + floder+"/";

            if (file.ContentLength / 1024 > fileSize)
                return "上传文件尺寸太大！";

            string[] temp = file.FileName.Split('.');
            string currentType = "." + temp[temp.Length - 1].ToLower();
            if (Array.IndexOf(filetype, currentType) == -1)
            {
                return "上传文件格式不正确！";
            }

            try
            {
                string uploadpath = HttpContext.Current.Server.MapPath(uploadUrl);
                string filename = DateTime.Now.ToString("yyyy-MM-dd-ss") + System.Guid.NewGuid() + currentType;
                file.SaveAs(uploadpath + filename);
                url = uploadUrl + filename;
            }
            catch { return "上传文件失败"; }
            return url;
        }
    }
}
